﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.storage.purchasein
{
    public partial class purchasein_putin_add : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "", Total_qty = "0";

        //绑定Session中的货品数据
        private void Bind()
        {
            DataTable dtList = new DataTable();

            dtList.Columns.Add("dgvID");
            dtList.Columns.Add("id");
            dtList.Columns.Add("areaname");
            dtList.Columns.Add("storagename");
            dtList.Columns.Add("productcode");
            dtList.Columns.Add("productname");
            dtList.Columns.Add("productshortname");
            dtList.Columns.Add("goodsclassname");
            dtList.Columns.Add("goodsunitname");
            dtList.Columns.Add("goodsspecname");
            dtList.Columns.Add("stackname");
            dtList.Columns.Add("guardname");
            dtList.Columns.Add("qty");

            DataTable dtData = ((purchasein_putin_class)Session["purchasein_putin"]).getList().Copy();

            foreach (DataRow dr in dtData.Rows)
            {
                DataRow drnew = dtList.NewRow();

                drnew["dgvID"] = (dtList.Rows.Count + 1).ToString();
                drnew["id"] = dr["id"].ToString();
                drnew["areaname"] = dr["areaname"].ToString();
                drnew["storagename"] = dr["storagename"].ToString();
                drnew["productcode"] = dr["productcode"].ToString();
                drnew["productname"] = dr["productname"].ToString();
                drnew["productshortname"] = dr["productshortname"].ToString();
                drnew["goodsclassname"] = dr["goodsclassname"].ToString();
                drnew["goodsunitname"] = dr["goodsunitname"].ToString();
                drnew["goodsspecname"] = dr["goodsspecname"].ToString();
                drnew["stackname"] = dr["stackname"].ToString();
                drnew["guardname"] = dr["guardname"].ToString();
                drnew["qty"] = dr["qty1"].ToString();

                dtList.Rows.Add(drnew);
            }

            rplist.DataSource = dtList;
            rplist.DataBind();
        }

        private void Reset()
        {
            uc_from_purchasebill.Reset();

            txt_suppliername.Text = "";
            txt_arrivaldate.Text = "";
            txt_phone.Text = "";
            txt_fax.Text = "";
            uc_from_warehouse.Reset();

            uc_from_area.SetByValue("");
            uc_from_storageset.SetByValue("");

            uc_from_product.clearValue();
            txt_qty.Text = "";

            ((purchasein_putin_class)Session["purchasein_putin"]).Reset();

            Total_qty = ((purchasein_putin_class)Session["purchasein_putin"]).Total_qty.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    ((purchasein_putin_class)Session["purchasein_putin"]).Reset();
                }
                catch
                {
                    Session.Add("purchasein_putin", new purchasein_putin_class(Session["connectionString"].ToString()));
                }

                Bind();

                Total_qty = ((purchasein_putin_class)Session["purchasein_putin"]).Total_qty.ToString();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                uc_from_area.setArea("");
                uc_from_storageset.SetByWarehouse("");
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            edowork.com.Model.billsInfo billsInfo = new billsInfo();
            edowork.com.Model.billsdetailInfo billsdetailInfo = new billsdetailInfo();

            billsInfo.APPID = uc_from_purchasebill.getValue();
            billsInfo.Billdate = uc_billdate.getValue();
            billsInfo.Billto = "";
            billsInfo.Billtype = "1003";
            billsInfo.Caseqty = "";
            billsInfo.Checkdate = "";
            billsInfo.Checkremark = "";
            billsInfo.Checkstu = "0";
            billsInfo.Checkuserid = "";
            billsInfo.Expressno = "";
            billsInfo.Freight = 0;
            billsInfo.Load_no = "";
            billsInfo.Logisticsid = "";
            billsInfo.M_date = "";
            billsInfo.M_ID = "";
            billsInfo.M_stu = "0";
            billsInfo.Remark = txt_remark.Text.Trim();
            billsInfo.Reserve_no = "";
            billsInfo.Shipto = uc_from_warehouse.getValue();
            billsInfo.Sysdate = DateTime.Now.ToString("yyyy-MM-dd");
            billsInfo.Transportid = "";
            billsInfo.Userid = Session["userid"].ToString();


            if (String.IsNullOrEmpty(billsInfo.APPID))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择采购单");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (String.IsNullOrEmpty(billsInfo.Billdate))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入开单日期");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (String.IsNullOrEmpty(billsInfo.Shipto))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请选择收货仓库");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            if (((purchasein_putin_class)Session["purchasein_putin"]).getListTotal() <= 0)
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入收货的货品信息");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            //取得采购入库单编码
            billsInfo.Billsno = SysID.SCR_BillID(Session["connectionString"].ToString(), ref alert_msg);
            billsdetailInfo.Billsno = billsInfo.Billsno;


            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch (Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;
                DataSet dsResult = null;

                //检查当前选择的年份与月份是否在结算日期之前
                sql = String.Format("select * from (select isnull(max(years+months), '') dates from sys_monthly_main) a where a.dates >='{0}{1}'", DateTime.Parse(billsInfo.Billdate).ToString("yyyy"), DateTime.Parse(billsInfo.Billdate).ToString("MM"));

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前选择的月份在结算日期之后。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //检查是否存在盘点单
                sql = String.Format("select csid from check_stock where warehouseid='{0}' and checkstu='0'", billsInfo.Shipto);

                dsResult = exec.ExecSQLQueryDataSet(sql, ref alert_msg, tran);

                if ((dsResult == null) || (dsResult.Tables[0].Rows.Count > 0))
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, "当前仓库正在盘点，不能进行出入库操作。");

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }


                //更新采购单的开单标记
                sql = String.Format("update purchase set b_open='1' where pcsid='{0}'", billsInfo.APPID);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //保存入bills表
                sql = String.Format(billsInfo.SQL_Insert(), billsInfo.Billsno, billsInfo.APPID, billsInfo.Billdate, billsInfo.Billtype, billsInfo.Remark, billsInfo.Userid,
                                                            billsInfo.Sysdate, billsInfo.Billto, billsInfo.Shipto, billsInfo.Transportid, billsInfo.Logisticsid,
                                                            billsInfo.Expressno, billsInfo.Load_no, billsInfo.Reserve_no, billsInfo.Caseqty, billsInfo.Freight,
                                                            billsInfo.Checkuserid, billsInfo.Checkstu, billsInfo.Checkdate, billsInfo.Checkremark,
                                                            billsInfo.M_stu, billsInfo.M_date, billsInfo.M_ID);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                DataTable dtData = ((purchasein_putin_class)Session["purchasein_putin"]).getList().Copy();

                foreach (DataRow dr in dtData.Rows)
                {
                    //保存入billsdetail表
                    sql = String.Format(billsdetailInfo.SQL_Insert(), billsdetailInfo.Billsno,
                                        dr["productcode"].ToString(), dr["Storageid"].ToString(), dr["qty1"].ToString(), 0);

                    result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                    if (result <= 0)
                    {
                        tran.Rollback();
                        tranutil.CloseConnection();

                        alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                        return;
                    }
                }

                tran.Commit();
                tranutil.CloseConnection();
            }

            Reset();

            Bind();

            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
        }

        //重置
        protected void btnReset_Click(object sender, EventArgs e)
        {
            Reset();

            Bind();
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string url = "/system/storage/purchasein/purchasein_putin.aspx";

            Response.Redirect(url);
        }

        //添加产品
        protected void btAddproduct_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            string areaid = uc_from_area.getValue();
            string storageid = uc_from_storageset.getValue();
            string productu_code = uc_from_product.getValue();
            string qty = txt_qty.Text.Trim();

            if (((purchasein_putin_class)Session["purchasein_putin"]).Add(areaid, storageid, productu_code, qty, ref alert_msg) == false)
            {
                alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            uc_from_product.clearValue();
            txt_qty.Text = "";
            
            Bind();

            Total_qty = ((purchasein_putin_class)Session["purchasein_putin"]).Total_qty.ToString();
            
        }

        //删除货品
        protected void rplist_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string id = e.CommandArgument.ToString();

            switch (e.CommandName)
            {
                case "Delete":
                    {
                        ((purchasein_putin_class)Session["purchasein_putin"]).Delect(id);

                        //查询
                        Bind();

                        Total_qty = ((purchasein_putin_class)Session["purchasein_putin"]).Total_qty.ToString();

                        alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Delete);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);


                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }

        //收货仓库选择
        protected void uc_from_warehouse_OnbtSelect_Click(object sender, EventArgs e)
        {
            string warehouseid = uc_from_warehouse.getValue();

            if (String.IsNullOrEmpty(warehouseid))
            {
                return;
            }

            uc_from_area.setArea(warehouseid);
            uc_from_storageset.SetByWarehouse("");

            ((purchasein_putin_class)Session["purchasein_putin"]).Reset();

            Total_qty = ((purchasein_putin_class)Session["purchasein_putin"]).Total_qty.ToString();

            Bind();
        }

        //库位的选择
        protected void uc_from_area_OnbtSelect_Click(object sender, EventArgs e)
        {
            string areadid = uc_from_area.getValue();

            if (String.IsNullOrEmpty(areadid))
            {
                return;
            }

            uc_from_storageset.setStorage(areadid);
        }

        //采购单选择
        protected void uc_from_purchasebill_OnbtSelect_Click(object sender, EventArgs e)
        {
            edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

            string pcsid = uc_from_purchasebill.getValue();

            string sql = String.Format("select a.arrivaldate, a.phone, a.fax, (select b.suppliername from supplier b where a.supplierid=b.supplierid) suppliername from purchase a where a.pcsid='{0}'", pcsid);

            DataSet ds = exec.ExecSQLQueryDataSet(sql);

            if (ds == null)
            {
                return;
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                txt_suppliername.Text = dr["suppliername"].ToString();
                txt_phone.Text = dr["phone"].ToString();
                txt_fax.Text = dr["fax"].ToString();
                txt_arrivaldate.Text = dr["arrivaldate"].ToString();
            }

            uc_list_purchasebill.pcsid = pcsid;
            uc_list_purchasebill.bind();

        }
    }
}